package com.gitee.auth;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

/**
 * Created by EalenXie on 2021/6/21 11:24
 */
@Configuration
@Import(AuthConfig.class)
@EnableResourceServer
public class ResourceServerAutoConfig extends ResourceServerConfigurerAdapter {


    @Resource
    private TokenStore tokenStore;
    @Resource
    public AuthenticationEntryPoint authenticationEntryPoint;


    /**
     * 配置访问策略
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/open/**","/say")
                .permitAll()
                .antMatchers("/**")
                .authenticated()
                // RBAC
//                .antMatchers("/api/**").hasAuthority("user")
//                .antMatchers("/admin/**").hasAuthority("admin")
                .and()
                .cors();
    }


    /**
     * 资源服务器配置
     */
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId("oauth2-resource")
                .authenticationEntryPoint(authenticationEntryPoint)
                .accessDeniedHandler((request, response, accessDeniedException) -> {
                    response.setStatus(HttpStatus.FORBIDDEN.value());
                    response.setCharacterEncoding(StandardCharsets.UTF_8.name());
                    response.setContentType(MediaType.APPLICATION_JSON_VALUE);
                    response.getWriter().write("{\"code\":\"403\",\"message\":\"Forbidden\",\"data\":\"" + accessDeniedException.getMessage() + "\"}");
                })
                .tokenStore(tokenStore)
        ;
    }


}
